package com.adcc.ags.cgw.job;

import com.adcc.ags.cgw.App;
import com.adcc.ags.cgw.entity.user.GWMode;
import com.adcc.ags.cgw.proxy.UserProxy;
import com.adcc.ags.cgw.utils.Constant;
import com.adcc.ags.cgw.utils.FileUtil;
import com.adcc.utility.codec.MD5;
import com.adcc.utility.log.Log;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.media.multipart.*;
import org.quartz.*;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 同步GW网关用户作业
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SyncGWUserListJob implements Job{

    // 同步网关用户URL
    private static final String SYNC_USERLIST_URL = "/user/getUserList";

    // 同步黑名单URL
    private static final String SYNC_BLACKLIST_URL = "/user/getBlackList";

    /**
     * 保存文件
     * @param file
     * @param destFilePath
     */
    private boolean backupFile(File file,String destFilePath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            fis = new FileInputStream(file);
            ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
            FileChannel inputChanneal = fis.getChannel();
            inputChanneal.read(buffer);
            inputChanneal.close();
            fos = new FileOutputStream(destFilePath);
            FileChannel outputChanneal = fos.getChannel();
            buffer.position(0);
            outputChanneal.write(buffer);
            outputChanneal.close();
            return true;
        }catch (Exception ex){
            Log.error("backupFile() error",ex);
            return false;
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException ex) {
                    Log.error("close FileInputStream error", ex);
                }
            }
            if(fos != null){
                try {
                    fos.close();
                }catch (IOException ex) {
                    Log.error("close FileOutputStream error",ex);
                }
            }
        }
    }

    /**
     * 同步文件文件
     * @param url
     * @param md5
     * @return
     */
    private Optional<String> syncFile(String url, String md5, String destFilePath){
        Client client = null;
        Response response =null;
        FileInputStream fis = null;
        try{
            FormDataMultiPart multiPart = new FormDataMultiPart();
            multiPart.field("MD5",md5);
            client = ClientBuilder.newClient().register(MultiPartFeature.class);
            response = client.target(url)
                                      .property(ClientProperties.CONNECT_TIMEOUT, 2000)
                                      .property(ClientProperties.READ_TIMEOUT, 120000)
                                      .request()
                                      .post(Entity.entity(multiPart, multiPart.getMediaType()));
            if(response.getStatus() == 200){
                FormDataMultiPart result  = response.readEntity(FormDataMultiPart.class);
                if(!Strings.isNullOrEmpty(result.getField("MD5").getValue())){
                    File file = result.getBodyParts().get(0).getEntityAs(File.class);
                    String strMD5 = MD5.getMD5(file);
                    if(!strMD5.equals(result.getField("MD5").getValue())){
                        return Optional.absent();
                    }else{
                        if(backupFile(file,destFilePath)){
                            return Optional.of(strMD5);
                        }else{
                            return Optional.absent();
                        }
                    }
                }else{
                    return Optional.absent();
                }
            }else{
                Log.error(SyncGWUserListJob.class.getName(),"sync userlist failed status:" + response.getStatus());
                return Optional.absent();
            }
        }catch (Exception ex){
            Log.error("syncFile() error",ex);
            return Optional.absent();
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException ex) {
                    Log.error("close file error",ex);
                }
            }
            if(response != null){
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            Log.info(SyncGMSUserListJob.class.getName(),"sync GW user list & black list begin");

            // 同步目标网关用户配置备份文件
            synchronized (UserProxy.getInstance().getGWMode()){
                if(UserProxy.getInstance().getGWMode() != GWMode.EMERGENCY){
                    String strSyncUserListDir = App.confPath + Constant.STRING_SYNC_USERLIST_DIR;
                    if(!FileUtil.isExist(strSyncUserListDir)){
                        if(!FileUtil.mkdir(strSyncUserListDir)){
                            Log.error("make dir " + strSyncUserListDir + " failed");
                        }
                    }
                    SchedulerContext sc = jobExecutionContext.getScheduler().getContext();
                    if(sc.containsKey(SyncGWUserListJob.class.getSimpleName()) && !Strings.isNullOrEmpty(sc.getString(SyncGWUserListJob.class.getSimpleName()))){
                        JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
                        String strUrl = sc.getString(SyncGWUserListJob.class.getSimpleName()) + SYNC_USERLIST_URL;
                        String strMD5 = Strings.nullToEmpty(map.getString("UserListMD5"));
                        String strDestFilePath = strSyncUserListDir + File.separator + Constant.STRING_USERLIST_FILE;
                        Optional<String> optUserList = syncFile(strUrl, strMD5, strDestFilePath);
                        if(optUserList.isPresent()){
                            Log.info("back up user list success MD5 code:" + optUserList.get());
                            map.put("UserListMD5", optUserList.get());
                        }
                        strUrl = sc.getString(SyncGWUserListJob.class.getSimpleName()) + SYNC_BLACKLIST_URL;
                        strMD5 = Strings.nullToEmpty(map.getString("BlackListMD5"));
                        strDestFilePath = strSyncUserListDir + File.separator + Constant.STRING_BLACKLIST_FILE;
                        Optional<String> optBlackList = syncFile(strUrl, strMD5, strDestFilePath);
                        if(optBlackList.isPresent()){
                            Log.info("back up black list success MD5 code:" + optBlackList.get());
                            map.put("BlackListMD5", optBlackList.get());
                        }
                    }
                }
            }
            Log.info(SyncGMSUserListJob.class.getName(),"sync GW user list & black list end");
        }catch (Exception ex){
            Log.error(SyncGWUserListJob.class.getName(),"execute() error",ex);
        }
    }
}
